package com.im.imservice.handler;


import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HeartbeatHandler extends ChannelDuplexHandler {

    /**
     * 心跳检测
     * @param ctx
     * @param paramObject
     * @throws Exception
     */
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object paramObject) throws Exception {

            if (paramObject instanceof IdleStateEvent) {
                IdleState event = ((IdleStateEvent) paramObject).state();
                switch (event) {
                    case READER_IDLE:
                        log.info("HeartbeatHandler-userEventTriggered-没有接收到:{}-的信息心跳信息，将断开连接回收资源", ctx.toString());
                        ctx.channel().close();
                        break;
                    case WRITER_IDLE:
                        log.info("HeartbeatHandler-userEventTriggered-写空闲");
                        break;
                    case ALL_IDLE:
                        log.info("HeartbeatHandler-userEventTriggered-读写空闲");
                        break;
                    default:
                        log.info("HeartbeatHandler-userEventTriggered-非法状态");
                        throw new IllegalStateException("非法状态！");
                }
            } else {
                super.userEventTriggered(ctx, paramObject);
            }
        }

}
